//
//  SSRefreshView.swift
//  weibo
//
//  Created by 邵帅 on 16/6/29.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit

enum SSRefreshType: Int{
    case Normal = 0
    case Pulling = 1
    case Loading = 2
}

class SSRefreshView: UIControl {
    
    // 定义一个属性，来记录当前状态
    var type: SSRefreshType = .Normal {
        
        didSet{
            
            switch type {
            case .Normal:
                
                messageLbl.text = "下拉刷新"
                arrowIcon.hidden = false
                arrowIcon.transform = CGAffineTransformIdentity
                
                loadingView.stopAnimating()
                
            case .Pulling:
                
                messageLbl.text = "释放更新"
                UIView.animateWithDuration(0.25, animations: {
                    
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Loading:
                
                messageLbl.text = "加载中..."
                arrowIcon.hidden = true
                loadingView.startAnimating()
                
                // 让视图停一下
                var inset = scrollView?.contentInset
                inset?.top = (inset?.top)! + self.bounds.height
                scrollView?.contentInset = inset!
                
                // 加载数据，回调
                // 利用control的父类方法去调用，值得改变方法
                sendActionsForControlEvents(.ValueChanged)
        }
     
    }
    
}
    

    // 初始化
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 添加布局控件
    private func setupUI() {
        
        var frame = self.frame
        frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 50)
        frame.origin.y = -50
        self.frame = frame
        
        addSubview(arrowIcon)
        addSubview(messageLbl)
        addSubview(loadingView)
        
        arrowIcon.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self.snp_centerX).offset(-40)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        messageLbl.snp_makeConstraints { (make) in
            
            make.center.equalTo(self.center)
        }
        
        loadingView.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self.snp_centerX).offset(-40)
            make.centerY.equalTo(self.snp_centerY)
        }
        
    }
    
    var scrollView: UIScrollView?
    
    // 被添加到自控件时，执行监听
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        // 可以吧这个下拉刷新的类，拓展到 UIScrollView里
        if newSuperview is UIScrollView {
            
            scrollView = newSuperview as? UIScrollView
            
            // 添加KVO监听
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    
    // 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 拖动中
        if scrollView!.dragging {
            
            if scrollView?.contentOffset.y < -140 && type == .Normal {
                
                type = .Pulling
            }else if scrollView?.contentOffset.y >= -140 && type == .Pulling {
                
                type = .Normal
            }
            
        }else {// 松手
            
            if scrollView?.contentOffset.y < -140 && type == .Pulling {
                
                type = .Loading
            }
        }
        
    }
    
    // 仿照系统的下拉完成方法
    func endRefreshing(){
        
        // 第一次网络请求时，系统会执行一次这个操作，我们应该判断一下，再修改内边距
        if type == .Loading {
            
            var inset = scrollView?.contentInset
            inset?.top = (inset?.top)! - self.bounds.height
            scrollView?.contentInset = inset!
        }
        
        type = .Normal
    }

    // 懒加载控件
    // 箭头
    private lazy var arrowIcon: UIImageView = {
        
        let imgView = UIImageView()
        
        imgView.image = UIImage(named:"tableview_pull_refresh")
        
        return imgView
    }()
    
    // 提示语
    private lazy var messageLbl: UILabel = {
        
        let lbl = UILabel()
        lbl.text = "下拉刷新"
        lbl.font = UIFont.systemFontOfSize(15)
        lbl.textColor = UIColor.darkGrayColor()
        
        return lbl
    }()
    
    // 菊花
    private lazy var loadingView: UIActivityIndicatorView = {
        
        let loadView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
        
        return loadView
    }()
    
}
